/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
 *
 * Copyright (C) 2019 KylinSoft  Co., Ltd.
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA.
 *
 */
#include "wallpaperui.h"
#include "ukcccommon.h"
#include "kbackgroundgroup.h"
#include <QScrollBar>

using namespace ukcc;
using namespace kdk;

WallpaperUi::WallpaperUi()
{
    setAttribute(Qt::WA_DeleteOnClose);
    m_uiLayout = new QVBoxLayout(this);
    m_uiLayout->setMargin(0);
    createObject();
    initUi();
    initColors();
    initSignals();
}

WallpaperUi::~WallpaperUi()
{

}

void WallpaperUi::createObject()
{
    m_wallpaperTitleLabel = new KLabel(this);
    m_wallpaperTitleLabel->setContentsMargins(16, 0, 0, 0);
    m_previewFrame = new UkccFrame(this);
    m_previewFrame->setFixedHeight(193);
    m_previewLabel = new PreviewLabel(m_previewFrame);
    m_previewLabel->setFixedSize(280, 160);
    m_settingGroup = new SettingGroup(this);
    m_colorGroup = new SettingGroup(m_settingGroup);
    m_addbuttonFrame = new UkccFrame(m_colorGroup);
    m_colorAddButton = new AddButton(m_addbuttonFrame);
    m_addbuttonlayout= new QHBoxLayout(m_addbuttonFrame);
    m_addbuttonlayout->setMargin(0);
    m_addbuttonlayout->addWidget(m_colorAddButton);
    m_colorFrame = new UkccFrame(m_colorGroup);
    m_colorLayout = new FlowLayout(m_colorFrame, 16, -1, -1);
    m_picBtnFrame = new UkccFrame(m_settingGroup);
    m_picFrame = new UkccFrame(m_picBtnFrame);
    m_picFrame->setLineWidth(0);
    m_pictureLayout = new FlowLayout(m_picFrame, 8, -1, -1);
    m_pictureLayout->setContentsMargins(16, 0, 16, 0);
    m_bottomFrame = new UkccFrame(m_picBtnFrame);
}

void WallpaperUi::initUi()
{
    // 1 桌面背景
    //~ contents_path /Wallpaper/Desktop Background
    m_wallpaperTitleLabel->setText(tr("Desktop Background"));

    // 2.1 背景
    m_modeWidget = new QWidget();
    QHBoxLayout* modeLayout = new QHBoxLayout(m_modeWidget);
    modeLayout->setContentsMargins(16, 0, 0, 0);
    modeLayout->setSpacing(0);
    //~ contents_path /Wallpaper/Background
    QLabel* modeLabel = new QLabel(tr("Background"), m_modeWidget);
    m_modeComboBox = new QComboBox(m_modeWidget);
    m_modeComboBox->setFixedWidth(240);
    modeLayout->addWidget(modeLabel);
    modeLayout->addStretch();
    modeLayout->addWidget(m_modeComboBox);

    // 2.2 显示方式
    m_typeWidget = new QWidget();
    QHBoxLayout* typeLayout = new QHBoxLayout(m_typeWidget);
    typeLayout->setContentsMargins(16, 0, 0, 0);
    typeLayout->setSpacing(0);
    //~ contents_path /Wallpaper/Type
    QLabel* typeLabel = new QLabel(tr("Type"), m_typeWidget);
    m_typeComboBox = new QComboBox(m_typeWidget);
    m_typeComboBox->setFixedWidth(240);
    typeLayout->addWidget(typeLabel);
    typeLayout->addStretch();
    typeLayout->addWidget(m_typeComboBox);

    QWidget* rightWidget = new QWidget();
    QVBoxLayout *rightVLayout = new QVBoxLayout(rightWidget);
    rightVLayout->addLayout(modeLayout);
    rightVLayout->addLayout(typeLayout);

    KBackgroundGroup* content = new KBackgroundGroup(m_previewFrame);
    content->addWidget(m_modeWidget);
    content->addWidget(m_typeWidget);

    QVBoxLayout *previewVLayout = new QVBoxLayout();
    previewVLayout->setContentsMargins(8, 0, 16, 0);
    previewVLayout->setSpacing(0);
    previewVLayout->addWidget(content);
    previewVLayout->addStretch();

    QHBoxLayout* previewHLayout = new QHBoxLayout(m_previewFrame);
    previewHLayout->setContentsMargins(16, 12, 16, 16);
    previewHLayout->addWidget(m_previewLabel);
    previewHLayout->addSpacing(0);
    previewHLayout->addLayout(previewVLayout);

    // 预览区域滚动条
    QScrollArea *previewScrollArea = new QScrollArea;
    previewScrollArea->viewport()->setAttribute(Qt::WA_TranslucentBackground);
    previewScrollArea->setStyleSheet("QScrollArea{background-color : transparent;}");
    previewScrollArea->verticalScrollBar()->setEnabled(false);
    previewScrollArea->horizontalScrollBar()->setEnabled(false);
    previewScrollArea->setWidgetResizable(true);
    previewScrollArea->setWidget(m_previewFrame);
    previewScrollArea->setFixedHeight(192);

    // 3.1 选择图片
    //~ contents_path /Wallpaper/Choose Picture
    QLabel* chooseLabel = new QLabel(tr("Choose Picture"), m_bottomFrame);

    // 3.2 本地图片
    //~ contents_path /Wallpaper/Local Pictures
    m_localBtn = new QPushButton(tr("Local Pictures"), m_bottomFrame);

    // 3.3 在线图片
    //~ contents_path /Wallpaper/Online Pictures
    m_onlineBtn = new QPushButton(tr("Online Pictures"), m_bottomFrame);

    // 3.4 恢复默认
    //~ contents_path /Wallpaper/Reset To Default
    m_resetBtn  = new QPushButton(tr("Reset To Default"), m_bottomFrame);

    QHBoxLayout *bottomLayout = new QHBoxLayout(m_bottomFrame);
    bottomLayout->setContentsMargins(16, 8, 16, 8);
    bottomLayout->addWidget(chooseLabel);
    bottomLayout->addStretch();
    bottomLayout->addWidget(m_localBtn);
    bottomLayout->addWidget(m_onlineBtn);
    bottomLayout->addWidget(m_resetBtn);

    QVBoxLayout *picBtnLayout = new QVBoxLayout(m_picBtnFrame);
    picBtnLayout->setMargin(0);
    picBtnLayout->setSpacing(0);
    picBtnLayout->addWidget(m_bottomFrame);
    picBtnLayout->addWidget(m_picFrame);

    m_colorGroup->addWidget(m_colorFrame);
    m_colorGroup->addWidget(m_addbuttonFrame);

    // 颜色滚动条
    m_colorScrollArea = new QScrollArea;
    m_colorScrollArea->viewport()->setAttribute(Qt::WA_TranslucentBackground);
    m_colorScrollArea->setStyleSheet("QScrollArea{background-color : transparent;}");
    m_colorScrollArea->verticalScrollBar()->setEnabled(false);
    m_colorScrollArea->setWidgetResizable(true);
    m_colorScrollArea->setWidget(m_colorGroup);
    m_colorScrollArea->setHidden(true);
    m_colorScrollArea->setMinimumHeight(200);

    m_settingGroup->addWidget(m_colorScrollArea);
    m_settingGroup->addWidget(m_picBtnFrame);

    // 图片区域滚动条
    QScrollArea *contentScrollArea = new QScrollArea;
    contentScrollArea->viewport()->setAttribute(Qt::WA_TranslucentBackground);
    contentScrollArea->setStyleSheet("QScrollArea{background-color: transparent;}");
    contentScrollArea->verticalScrollBar()->setProperty("drawScrollBarGroove", false);
    contentScrollArea->setWidgetResizable(true);
    contentScrollArea->setFrameShape(QFrame::Box);
    contentScrollArea->setFrameShadow(QFrame::Plain);
    contentScrollArea->setWidget(m_settingGroup);

    m_uiLayout->addWidget(m_wallpaperTitleLabel);
    m_uiLayout->addWidget(previewScrollArea);
    m_uiLayout->addWidget(contentScrollArea);

    connect(m_modeComboBox, QOverload<const QString&>::of(&QComboBox::activated), this, [=](const QString &mode) {
        modeComboBoxSlot();
    });
}

void WallpaperUi::initColors()
{
    QStringList colors;
    colors << "#2d7d9a" << "#018574" << "#107c10" << "#10893e" << "#038387" << "#486860" << "#525e54" << "#7e735f" << "#4c4a48" << "#000000";
    colors << "#ff8c00" << "#e81123" << "#d13438" << "#c30052" << "#bf0077" << "#9a0089" << "#881798" << "#744da9" << "#8764b8" << "#e9e9e9";

    for (QString color : colors){
        QPushButton *button = new QPushButton(m_colorFrame);
        button->setFixedSize(QSize(48, 48));
        QString btnQss = QString("QPushButton{background: %1; border: none; border-radius: 4px;}").arg(color);
        button->setStyleSheet(btnQss);

        connect(button, &QPushButton::clicked, [=, color]() {
            picButtonClickSlot(color);
        });
        m_colorLayout->addWidget(button);
    }
}

void WallpaperUi::initSignals()
{
    connect(m_typeComboBox, QOverload<const QString&>::of(&QComboBox::activated), this, [=](const QString &type){
        typeComboBoxSlot();
    });

    connect(m_localBtn, &QPushButton::clicked, this, [=](){
        localBtnClickSlot();
    });

    connect(m_onlineBtn, &QPushButton::clicked, this, [=](){
        onlineBtnClickSlot();
    });

    connect(m_resetBtn, &QPushButton::clicked, this, [=](){
        resetBtnClickSlot();
    });

    connect(m_colorAddButton, &AddButton::clicked, this, [=](){
        colorAddButtonSlot();
    });
}

void WallpaperUi::modeComboBoxSlot() {
    if (m_modeComboBox->currentData().toString() == "picture") {
        showPictures();
        UkccCommon::buriedSettings("Wallpaper", QString("Background"), QString("select"), "picture");
    } else {
        showColors();
        UkccCommon::buriedSettings("Wallpaper", QString("Background"), QString("select"), "color");
    }
}

void WallpaperUi::picButtonClickSlot(QString color) {
    m_previewLabel->setColor(color);
    m_previewLabel->update();
    Q_EMIT wallpaperChanged(m_modeComboBox->currentData().toString(), color);
}

void WallpaperUi::resetBtnClickSlot() {
    Q_EMIT resetButtonClicked();
}

void WallpaperUi::onlineBtnClickSlot() {
    Q_EMIT onlineButtonClicked();
}

void WallpaperUi::localBtnClickSlot() {
    Q_EMIT localButtonClicked();
}

void WallpaperUi::typeComboBoxSlot() {
    m_previewLabel->setMode(m_typeComboBox->currentData().toString());
    m_previewLabel->update();
    Q_EMIT typeChanged(m_typeComboBox->currentData().toString());
}

void WallpaperUi::colorAddButtonSlot() {
    ColorDialog *colordialog = new ColorDialog(this);
    colordialog->setAttribute(Qt::WA_DeleteOnClose);
    connect(colordialog, &ColorDialog::colorSelected, this, [=](QColor color){
        colorDialogSlot(color);
    });
    colordialog->exec();
}

void WallpaperUi::colorDialogSlot(QColor color) {
    m_previewLabel->setColor(color.name());
    m_previewLabel->update();
    Q_EMIT wallpaperChanged(m_modeComboBox->currentData().toString(), color.name());
}

void WallpaperUi::setWallpaperModes(const QStringList &modeList, const QStringList &modeDataList)
{
    if (modeList.size() != modeDataList.size()) {
        qWarning()<<"modeList.size():"<<modeList.size()<<" != modeDataList.size():"<<modeDataList.size();
        return;
    }
    m_modeComboBox->clear();
    for (int i = 0; i < modeList.size(); ++i) {
        m_modeComboBox->addItem(modeList.at(i), modeDataList.at(i));
    }
}

void WallpaperUi::setDisplayTypes(const QStringList &typeList, const QStringList &typeDataList)
{
    if (typeList.size() != typeDataList.size()) {
        qWarning()<<"typeList.size():"<<typeList.size()<<" != typeDataList.size():"<<typeDataList.size();
        return;
    }
    m_typeComboBox->clear();
    for (int i = 0; i < typeList.size(); ++i) {
        m_typeComboBox->addItem(typeList.at(i), typeDataList.at(i));
    }
}

void WallpaperUi::setWallpaperMode(const QString &mode, const QString &data)
{
    m_modeComboBox->setCurrentText(mode);
    if (m_modeComboBox->currentData().toString() == "color") {
        m_colorScrollArea->setHidden(false);
        currentFile = "";
        QColor color(data);
        m_previewLabel->setColor(color);
        m_previewLabel->update();
        if (prePictureUnit != nullptr) {
            prePictureUnit->changeClickedFlag(false);
            prePictureUnit->setStyleSheet("border-width: 0px;");
            prePictureUnit = nullptr;
        }
    } else {
        m_colorScrollArea->setHidden(true);
        currentFile = data;
        m_previewLabel->setLocalPixmap(QPixmap(currentFile));
        m_previewLabel->update();
        resetClickedPic();
    }
}

void WallpaperUi::setDisplayType(const QString &type)
{
    m_typeComboBox->setCurrentText(type);
    m_previewLabel->setMode(m_typeComboBox->currentData().toString());
    m_previewLabel->update();
}

void WallpaperUi::setPicturesFile(QList<PictureInfo*> picInfoList) {
    bool hitCurrentFile = false;
    for (int i = 0; i < picInfoList.size(); ++i) {
        QString name = picInfoList.at(i)->fileName;
        bool clicked = false;
        if (name == currentFile) {
            clicked = true;
            hitCurrentFile = true;
        }
        PictureUnit *picUnit = new PictureUnit();
        if (picUnit == nullptr) {
            continue;
        }
        picUnit->setPixmap(picInfoList.at(i)->pixmap);
        picUnit->setFilenameText(name);
        createPictureUnit(picUnit, clicked);
    }
    // 是自定义的图片
    if (!currentFile.isEmpty() && !hitCurrentFile && QFile::exists(currentFile)) {
        m_previewLabel->setLocalPixmap(QPixmap(currentFile));
        m_previewLabel->update();
    }
}

void WallpaperUi::createPictureUnit(PictureUnit* picUnit, const bool &clicked) {
    if (picUnit == nullptr)
        return;
    const QString &filename = picUnit->filenameText();
    if (clicked) {
        prePictureUnit = picUnit;
        picUnit->changeClickedFlag(true);
        m_previewLabel->setLocalPixmap(QPixmap(filename));
        m_previewLabel->update();
    }
    connect(picUnit, &PictureUnit::clicked, [=](QString file){
        if (prePictureUnit) {
            prePictureUnit->changeClickedFlag(false);
        }
        prePictureUnit = picUnit;
        m_previewLabel->setLocalPixmap(QPixmap(file));
        m_previewLabel->update();
        Q_EMIT wallpaperChanged("picture", file);
    });
    m_pictureLayout->addWidget(picUnit);
}

void WallpaperUi::showPictures()
{
    m_colorGroup->setHidden(true);
    m_typeWidget->setHidden(false);
    m_picFrame->setHidden(false);
    m_bottomFrame->setHidden(false);
    m_colorScrollArea->setHidden(true);
}

void WallpaperUi::showColors()
{
    m_picFrame->setHidden(true);
    m_typeWidget->setHidden(true);
    m_colorGroup->setHidden(false);
    m_bottomFrame->setHidden(true);
    m_colorScrollArea->setHidden(false);
}

void WallpaperUi::resetClickedPic() {
    if (prePictureUnit != nullptr) {
        prePictureUnit->changeClickedFlag(false);
        prePictureUnit = nullptr;
    }
    for (int i = m_pictureLayout->count() - 1; i >= 0; --i) {
        QLayoutItem *it = m_pictureLayout->itemAt(i);
        PictureUnit *picUnit = static_cast<PictureUnit*>(it->widget());
        if (currentFile == picUnit->filenameText()) {
            picUnit->changeClickedFlag(true);
            prePictureUnit = picUnit;
        }
    }
}
